package com.jerry.template.module.mainpage.shouye.image.fragment;

import android.support.annotation.NonNull;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jerry.template.R;
import com.jerry.template.base.BaseFragment;
import com.jerry.template.constant.Urls;
import com.jerry.template.module.mainpage.shouye.image.adapter.ImageAdapter;
import com.jerry.template.module.mainpage.shouye.image.entity.ImageMessage;
import com.jerry.template.utils.EventMessage;
import com.jerry.template.utils.OkHttpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by chenhuan on 2016/5/9.
 */
public class ImageFragment extends BaseFragment{
    private List<ImageMessage.DataBean.DataBean1> data = new ArrayList<>();

    @BindView(R.id.pull_ListView)
    PullToRefreshListView listView;

    private ImageMessage imageMessage;

    private ImageAdapter imageAdapter;

    private int index = 1;

    public ImageFragment(){
    }

    @Override
    protected int getLayoutId(){
        return R.layout.frag_image;
    }

    @Override
    protected void loadData(){
        Map<String, Object> params = new HashMap<>();
        params.put("essence", index);
        OkHttpUtils.postSubmitForm(Urls.IMAGE_URL, null);
    }

    @Override
    protected void initViews(){
        imageAdapter = new ImageAdapter(getActivity(), data);
        listView.setAdapter(imageAdapter);
        listView.setMode(PullToRefreshBase.Mode.BOTH);

        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>(){
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView){
                index = 1;
                data.clear();
                loadData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView){
                index++;
                loadData();
            }
        });

    }

    @Override
    protected void postEventResult(@NonNull EventMessage message){
        if(message != null){
            if(Urls.IMAGE_URL.equals(message.type)){
                listView.onRefreshComplete();
                Gson gson = new Gson();
                //String result =  message.result;
                imageMessage = gson.fromJson(message.result, ImageMessage.class);
                data.addAll(imageMessage.getData().getData());
                imageAdapter.notifyDataSetChanged();
            }

        }
    }
}